package com.mass.core.sys.user.services.impl;

import com.mass.core.sys.authority.dao.SysAuthorityMapper;
import com.mass.core.sys.authority.model.SysAuthorityExample;
import com.mass.core.sys.user.model.SysUserExample;
import com.mass.core.sys.userrole.dao.SysUserAndRoleMapper;
import com.mass.core.sys.userrole.model.SysUserAndRoleExample;
import com.mass.core.utils.AjaxResponse;
import com.mass.core.utils.DateUtils;
import com.mass.core.utils.PingYin;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import com.mass.core.sys.user.dao.SysUserMapper;
import com.mass.core.sys.user.model.SysUser;
import com.mass.core.sys.user.services.SysUserServices;
import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class SysUserServicesImpl implements SysUserServices {

	@Autowired(required = false)
	private SysUserMapper sysUserMapper;     //用户接口

	@Autowired(required = false)
	private SysAuthorityMapper sysAuthorityMapper;  //   注入权限接口

	@Autowired(required = false)
	private SysUserAndRoleMapper sysUserAndRoleMapper; // 注入用户角色中间表


	/**
	 * 验证系统用户帐号是否存在
	 * @param account           用户帐号
	 * @return
	 */
	
	public SysUser checkAccountIsExist(String account) {
		SysUserExample sysUserExample = new SysUserExample();
		sysUserExample.createCriteria().andAccountEqualTo(account).andDelFlagEqualTo(0);
		List<SysUser> sysUserList = sysUserMapper.selectByExample(sysUserExample);
		if(!ObjectUtils.isEmpty(sysUserList))
			return sysUserList.get(0);
		else
			return null;
	}

	/**
	 * 验证用户登录
	 *
	 * @param username  用户账号
	 * @param password  用户密码
	 * @return  如果有用户则返回
	 */
	
	public SysUser checkLogin(String username, String password) {
		SysUserExample sysUserExample = new SysUserExample();
		SysUserExample.Criteria criteria = sysUserExample.createCriteria();
		criteria.andAccountEqualTo(username)
				.andPasswordEqualTo(DigestUtils.md5Hex(password))
		.andDelFlagEqualTo(0);
		List<SysUser> sysUserList = sysUserMapper.selectByExample(sysUserExample);
		if(!ObjectUtils.isEmpty(sysUserList))
			return sysUserList.get(0);
		else
			return null;
	}

    /**
     * 修改用户信息
     * @param sysUser
     * @param session
     * @return
     */
    
    @Transactional
    public AjaxResponse updateSysUser(SysUser sysUser, HttpSession session) {
        Object object =  session.getAttribute("sysUser");
        if(!ObjectUtils.isEmpty(object) && !ObjectUtils.isEmpty(sysUser)){
            SysUser sessionSysUser = (SysUser)object;
            if(!ObjectUtils.isEmpty(sysUser.getName()))
                sessionSysUser.setName(sysUser.getName());
            if(!ObjectUtils.isEmpty(sysUser.getEmployeeHead()))
                sessionSysUser.setEmployeeHead(sysUser.getEmployeeHead());
            if(!ObjectUtils.isEmpty(sysUser.getRoleId()))
                sessionSysUser.setRoleId(sysUser.getRoleId());
            session.setAttribute("sysUser",sessionSysUser);
        }
        if(!ObjectUtils.isEmpty(sysUser.getPassword()))
        	sysUser.setPassword(sysUser.getPassword());
        return AjaxResponse.success(sysUserMapper.updateByPrimaryKeySelective(sysUser));
    }

    /**
	 * 添加用户 DigestUtils.md5Hex("666666")
	 */
	
	@Transactional
	public AjaxResponse insert(SysUser sysUser) {
        sysUser.setPassword(DigestUtils.md5Hex("666666"));
        sysUser.setCreateTime(DateUtils.getDate());
        sysUser.setDelFlag(0);
        sysUser.setEnabled(1);
        sysUser.setRoleId((long) 0);
        int number = sysUserMapper.insertSelective(sysUser);
        if(number>0) {
            if (!ObjectUtils.isEmpty(sysUser.getSysAuthorityList()))//授权
                sysAuthorityMapper.insertByBatch(sysUser.getSysAuthorityList());
            if (!ObjectUtils.isEmpty(sysUser.getSysRoleList()))//添加角色
                sysUserAndRoleMapper.insertByBatch(sysUser.getId(), sysUser.getSysRoleList());
        }
		return AjaxResponse.success(number);
	}

	/**
	 *
	 * @param sysUser
	 * @return
	 */
	
	public AjaxResponse findUserList(SysUser sysUser,Integer pageIndex,Integer pageSize) {
		SysUserExample sysUserExample = new SysUserExample();
		if(!ObjectUtils.isEmpty(pageIndex)){
			sysUserExample.setPageIndex((pageIndex-1)*pageSize);
			sysUserExample.setPageSize(pageSize);
		}
		SysUserExample.Criteria criteria = sysUserExample.createCriteria();
		criteria.andDelFlagEqualTo(0);   //正常
		if(!ObjectUtils.isEmpty(sysUser)){
			if(!ObjectUtils.isEmpty(sysUser.getAccount()))
				criteria.andAccountLike("%"+sysUser.getAccount()+"%");
			if(!ObjectUtils.isEmpty(sysUser.getName()))
				criteria.andNameLike("%"+sysUser.getName()+"%");
			if(!ObjectUtils.isEmpty(sysUser.getPassword()))
				criteria.andPasswordEqualTo(DigestUtils.md5Hex(sysUser.getPassword()));
			if(!ObjectUtils.isEmpty(sysUser.getUnionId()))
				criteria.andUnionIdEqualTo(sysUser.getUnionId());
		}
		List<SysUser> sysUserList = sysUserMapper.selectByExample(sysUserExample);
		long count = sysUserMapper.countByExample(sysUserExample);
		return AjaxResponse.success("ok",sysUserList,count,pageIndex);
	}

	/**
	 * 查询所有权限
	 * @return
	 */
	
	public AjaxResponse findAutorityAll(Long userId) {
		return AjaxResponse.success(sysUserMapper.findAutorityAll(userId,(long)0));
	}

	/**
	 *修改用户权限
	 * @param sysUser
	 * @return
	 */
	
	@Transactional
	public AjaxResponse updateAutority(SysUser sysUser) {
		if(!ObjectUtils.isEmpty(sysUser)){
			SysAuthorityExample sysAuthorityExample = new SysAuthorityExample();
			sysAuthorityExample.createCriteria()
					.andTypesEqualTo(2) //用户类型
					.andRoleOrUserIdEqualTo(sysUser.getId());
			//删除用户权限
			sysAuthorityMapper.deleteByExample(sysAuthorityExample);
			if(!ObjectUtils.isEmpty(sysUser.getSysAuthorityList()))//授权
			sysAuthorityMapper.insertByBatch(sysUser.getSysAuthorityList());

			SysUserAndRoleExample sysUserAndRoleExample = new SysUserAndRoleExample();
			sysUserAndRoleExample.createCriteria()
					.andUserIdEqualTo(sysUser.getId());
			//删除角色
			sysUserAndRoleMapper.deleteByExample(sysUserAndRoleExample);
			if(!ObjectUtils.isEmpty(sysUser.getSysRoleList()))//添加角色
			sysUserAndRoleMapper.insertByBatch(sysUser.getId(),sysUser.getSysRoleList());

			int number = sysUserMapper.updateByPrimaryKeySelective(sysUser);
			return AjaxResponse.success(number);
		}else{
			return AjaxResponse.error("no");
		}
	}
	public List<SysUser> findSysUserByUserId(List<Long> ids) {
		return sysUserMapper.findSysUserByUserId(ids);
	}

	@Transactional
	public int updateSysUserInfo(SysUser sysUser) {
		sysUser.setAccount(null);
		sysUser.setPassword(null);
		return sysUserMapper.updateByPrimaryKeySelective(sysUser);
	}

	public SysUser findSysUserByUserId(Long userId) {
		return sysUserMapper.selectByPrimaryKey(userId);
	}

	public SysUser findSysUserByOpenId(String openId) {
		SysUserExample sysUserExample = new SysUserExample();
		sysUserExample.createCriteria().andOpenIdEqualTo(openId);
		List<SysUser> sysUsers = sysUserMapper.selectByExample(sysUserExample);
		if(sysUsers.size()> 0){
			return sysUsers.get(0);
		}else{
			return null;
		}
	}
	@Transactional
	public int unlock(String password,Long userId) {
		SysUserExample sysUserExample = new SysUserExample();
		sysUserExample.createCriteria()
		.andPasswordEqualTo(DigestUtils.md5Hex(password))
		.andIdEqualTo(userId);
		SysUser sysUser = new SysUser();
		sysUser.setLockScreen(0);
		return sysUserMapper.updateByExampleSelective(sysUser, sysUserExample);
	}

	@Override
	public AjaxResponse selectUserPage(SysUser sysUser, Integer pageIndex,
			Integer pageSize) {
		SysUserExample sysUserExample = new SysUserExample();
		if(!ObjectUtils.isEmpty(pageIndex)){
			sysUserExample.setPageIndex((pageIndex-1)*pageSize);
			sysUserExample.setPageSize(pageSize);
		}
		SysUserExample.Criteria criteria = sysUserExample.createCriteria();
		criteria.andDelFlagEqualTo(0);   //正常
		criteria.andRoleNameNotNull();
		criteria.andUnionIdNotNull();
		if(!ObjectUtils.isEmpty(sysUser)){
			if(!ObjectUtils.isEmpty(sysUser.getAccount()))
				criteria.andAccountLike("%"+sysUser.getAccount()+"%");
			if(!ObjectUtils.isEmpty(sysUser.getName()))
				criteria.andNameLike("%"+sysUser.getName()+"%");
			if(!ObjectUtils.isEmpty(sysUser.getPassword()))
				criteria.andPasswordEqualTo(DigestUtils.md5Hex(sysUser.getPassword()));
			if(!ObjectUtils.isEmpty(sysUser.getUnionCode()))
				criteria.andUnionCodeLike("%"+sysUser.getUnionCode()+"%");
		}
		List<SysUser> sysUserList = sysUserMapper.selectByExample(sysUserExample);
		long count = sysUserMapper.countByExample(sysUserExample);
		return AjaxResponse.success("ok",sysUserList,count,pageIndex);
	}

	@Override
	public SysUser selectById(Long id) {
		return sysUserMapper.selectByPrimaryKey(id);
	}

	//会员模块调用 用作判断是否设置为操作人员
	@Override
	public long findUserListByBaseId(SysUser sysUser,Integer pageIndex,Integer pageSize) {
		SysUserExample sysUserExample = new SysUserExample();
		if(!ObjectUtils.isEmpty(pageIndex)){
			sysUserExample.setPageIndex((pageIndex-1)*pageSize);
			sysUserExample.setPageSize(pageSize);
		}
		SysUserExample.Criteria criteria = sysUserExample.createCriteria();
		criteria.andDelFlagEqualTo(0);   //正常
		criteria.andAPersonalBaseIdEqualTo(sysUser.getId());
		long count = sysUserMapper.countByExample(sysUserExample);
		return count;
	}
	
	//会员管理模块调用  新增操作人员
	@Override
	public AjaxResponse insertUser(SysUser sysUser) {
		PingYin py = new PingYin();
		sysUser.setAccount(py.getPingYin(sysUser.getName())+sysUser.getaPersonalBaseId());
		sysUser.setPassword(DigestUtils.md5Hex("666666"));
        sysUser.setCreateTime(DateUtils.getDate());
        sysUser.setDelFlag(0);
        sysUser.setEnabled(1);
        sysUser.setRoleId((long) 0);
        int number = sysUserMapper.insertSelective(sysUser);
        if(number>0) {
            if (!ObjectUtils.isEmpty(sysUser.getSysAuthorityList()))//授权
                sysAuthorityMapper.insertByBatch(sysUser.getSysAuthorityList());
            if (!ObjectUtils.isEmpty(sysUser.getSysRoleList()))//添加角色
                sysUserAndRoleMapper.insertByBatch(sysUser.getId(), sysUser.getSysRoleList());
        }
		return AjaxResponse.success(py.getPingYin(sysUser.getAccount()),number);
	}
	
}
